package admin

import (
	"blogs/models"
	"blogs/utils"
	"errors"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// 关于对象的操作
type LoginController struct {
	beego.Controller
}

// @Title GetInfo
// @Description 拉取用户信息
// @Success 200
// @router / [get]
func (o *LoginController) GetInfo() {
	token := o.Ctx.Input.Header("X-Token")
	Secrect, _ := beego.AppConfig.String("Secrect")
	str, _ := ParseToken(token, Secrect)

	user := models.User{}
	utils.DB.Where("username=?", str).Select("username", "id").Find(&user)

	o.Data["json"] = map[string]interface{}{
		"code": true,
		"data": user,
		"msg":  "",
	}
	o.ServeJSON()
	return

}

// @Title Login
// @Description 用户登录
// @Success 200
// @router / [post]
func (o *LoginController) Login() {

	username := o.GetString("username")
	password := o.GetString("password")
	if username == "" || password == "" {
		o.Data["json"] = map[string]interface{}{
			"code": false,
			"data": "用户名密码不能为空",
			"msg":  "用户名密码不能为空",
		}
		o.ServeJSON()
		return
	}
	user := []models.User{}
	utils.DB.Where("username =? and password= ?", username, password).Find(&user)
	if len(user) > 0 {
		// 有内容
		Secrect, _ := beego.AppConfig.String("Secrect")
		str, _ := CreateToken(username, Secrect)
		o.Data["json"] = map[string]interface{}{
			"code":  true,
			"token": str,
			"msg":   "登录成功",
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"code": false,
		"data": "用户名密码错误",
		"msg":  "用户名密码错误",
	}
	o.ServeJSON()
}

// @Title Logout
// @Description 用户退出
// @Success 200
// @router / [delete]
func (o *LoginController) Logout() {
	token := o.Ctx.Input.Header("X-Token")
	Secrect, _ := beego.AppConfig.String("Secrect")
	str, _ := ParseToken(token, Secrect)
	_, err := DeleteToken(str, Secrect)
	if err != nil {
		o.Data["json"] = map[string]interface{}{
			"code": false,
			"data": "删除token失败",
			"msg":  "删除token失败",
		}
		o.ServeJSON()
		return
	}
	o.Data["json"] = map[string]interface{}{
		"code": false,
		"data": "删除token成功",
		"msg":  "删除token成功",
	}
	o.ServeJSON()

}

//设置token
func CreateToken(uid, secret string) (string, error) {
	at := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid": uid,
		"exp": time.Now().Add(time.Minute * 15).Unix(), // 15分钟
	})
	token, err := at.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}
	return token, nil
}

//删除token
func DeleteToken(uid, secret string) (string, error) {
	at := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid": uid,
		"exp": time.Now().Add(time.Second * 1).Unix(), // 1秒
	})
	token, err := at.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}
	return token, nil
}

// 解析token
func ParseToken(token string, secret string) (string, error) {
	claim, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if err != nil {
		return "", err
	}
	return claim.Claims.(jwt.MapClaims)["uid"].(string), errors.New("正确")
}
